import 'package:elephant_fish/http/core/hi_error.dart';
import 'package:elephant_fish/model/room_entity.dart';
import 'package:elephant_fish/model/video.dart';
import 'package:elephant_fish/widget/video_card.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_pickers/more_pickers/init_data.dart';
import 'package:flutter_pickers/pickers.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';

class IndexNearByPage extends StatefulWidget {
  final String categoryName;
  final String cityName;
  final String sex;

  const IndexNearByPage({Key key, this.categoryName, this.cityName, this.sex}) : super(key: key);

  @override
  _IndexNearByPageState createState() => _IndexNearByPageState();
}

class _IndexNearByPageState extends State<IndexNearByPage> with AutomaticKeepAliveClientMixin{
  List<Video> videoList = [];
  List<RoomEntity> roomList = [];
  int pageIndex = 1;
  bool _loading = false;
  String cityName = '武汉';
  String sex = '男';
  ScrollController _scrollController = ScrollController();
  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      var dis = _scrollController.position.maxScrollExtent -
          _scrollController.position.pixels;
      //当距离底部不足300时加载更多
      if (dis < 300 && !_loading) {
        _loadData(loadMore: true);
      }
    });
    _loadData();
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xff140c3c),
      body:  Stack(
          children: [
            Row(
              children: [
                Padding(padding: EdgeInsets.only(left: 6,top: 20),
                  child: InkWell(
                    child: ClipRRect(
                      borderRadius: BorderRadius.all(Radius.circular(15.5)),
                      child: Container(
                        height: 30.5,
                        decoration: BoxDecoration(
                            gradient: LinearGradient(
                              begin: Alignment.topCenter,
                              end: Alignment.bottomCenter,
                              colors: [Color(0xffff6091),Color(0xffd71047)],
                            )
                        ),
                        child:  Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Padding(padding: EdgeInsets.only(left: 12,top:3,bottom: 8,right: 12),
                              child: Text(cityName,style: TextStyle(fontSize: 14,color: Color(0xffffffff),),
                              ),
                            )
                          ],
                        )
                      ),

                    ),
                    onTap: (){
                      showCity();
                    },
                  )
                ),
                Padding(padding: EdgeInsets.only(left: 11, top: 20),
                    child: InkWell(
                      child: ClipRRect(
                        borderRadius: BorderRadius.all(Radius.circular(15.5)),
                        child: Container(
                          height: 30.5,
                          decoration: BoxDecoration(
                              gradient: LinearGradient(
                                begin: Alignment.topCenter,
                                end: Alignment.bottomCenter,
                                colors: [Color(0xffff6091),Color(0xffd71047)],
                              )
                          ),
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Padding(padding: EdgeInsets.only(left: 15.5,top:3,bottom: 8,right: 15.5),
                                child: Text(sex,style: TextStyle(fontSize: 14,color: Color(0xffffffff),),
                                ),
                              )
                            ],
                          )
                        ),

                      ),
                      onTap: (){
                        showSex();
                      },
                    )
                )
              ],
            ),
            Padding(padding: EdgeInsets.only(top: 54),

              child:  StaggeredGridView.countBuilder(
                  shrinkWrap: true,
                  controller: _scrollController,
                  physics: const AlwaysScrollableScrollPhysics(),
                  padding: EdgeInsets.only(left: 3,right: 3,top: 3),
                  crossAxisCount: 4,
                  crossAxisSpacing: 4,
                  itemCount: videoList.length,
                  itemBuilder: (BuildContext context, int index) {
                    //有banner时第一个item位置显示banner
                    return VideoCard(roomEntity: roomList[index]);
                  },staggeredTileBuilder: (int index) {
                return StaggeredTile.fit(2);
              }) ,
            )
          ],
      ),
    );
  }

  void _loadData({loadMore = false})async {
    _loading = true;
    if(!loadMore){
      pageIndex = 1;
    }
    var currentIndex = pageIndex + (loadMore ? 1 : 0);
    print('loading:currentIndex:$currentIndex');
    try{
      // Video result =  await VideoDao.get(widget.categoryName,pageIndex: currentIndex, pageSize: 10);
      // setState(() {
      //   if (loadMore) {
      //     if (result.videoList.isNotEmpty) {
      //       //合成一个新数组
      //       videoList = [...videoList, ...result.videoList];
      //       pageIndex++;
      //     }
      //   } else {
      //     videoList = result.videoList;
      //   }
      // });
      // Future.delayed(Duration(milliseconds: 1000), () {
      //   _loading = false;
      // });
      for(int i = 0; i < 5; i ++){
        Video video = Video(i, 'https://img0.baidu.com/it/u=3101694723,748884042&fm=26&fmt=auto&gp=0.jpg', '测试', '123213',i.toString());
        videoList.add(video);
      }
      for(int i = 0; i < 5; i ++){
        Video video = Video(i, 'https://img2.baidu.com/it/u=360400461,2955275651&fm=26&fmt=auto&gp=0.jpg', '测试1', 'qweqeq',i.toString());
        videoList.add(video);
      }
    }on NeedAuth catch(e){
      print(e);
    }on HiNetError catch(e){
      print(e);
    }

  }

  showCity()async{
    String initProvince = '湖北省', initCity = '武汉市';
    Pickers.showAddressPicker(
      context,
      initProvince: initProvince,
      initCity: initCity,
      initTown: null,
      onConfirm: (p, c, t) {
        setState(() {
          initProvince = p;
          initCity = c;
          cityName = c;
        });
      },
    );
  }

  showSex() async{
    String initData = sex;
    Pickers.showSinglePicker(context,
        data: PickerDataType.sex,
        selectData: initData,
        onConfirm: (p) {
          setState(() {
            initData = p;
            sex = p;
          });
        }, onChanged: (p) => print('数据发生改变：$p'));
  }

  @override
  bool get wantKeepAlive => true;

}
